import cv2
from matplotlib import pyplot as plt
import matplotlib
import baseconf

matplotlib.use('TkAgg')

fristvideo_path = baseconf.BASE_DISK+":/datasets_path/tianchivit/fristvideo"

cap = cv2.VideoCapture(fristvideo_path+'./43.avi')


while cap.isOpened():
    _,img_1 = cap.read()
    _,img_2 = cap.read()
    _,img_3 = cap.read()
    _,img_4 = cap.read()

    _,img_5 = cap.read()
    _,img_6 = cap.read()
    _,img_7 = cap.read()
    _,img_8 = cap.read()
    _,img_9 = cap.read()
    # find difference between two frames
    diff = cv2.absdiff(img_1, img_2)



    # to convert the frame to grayscale
    diff_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

    # apply some blur to smoothen the frame
    diff_blur = cv2.GaussianBlur(diff_gray, (5, 5), 0)

    # to get the binary image
    _, thresh_bin = cv2.threshold(diff_blur, 40, 255, cv2.THRESH_BINARY)

    # to find contours
    contours, hierarchy = cv2.findContours(thresh_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # to draw the bounding box when the motion is detected
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if cv2.contourArea(contour) > 300:
            cv2.rectangle(img_1, (x, y), (x + w, y + h), (0, 255, 0), 2)
    # cv2.drawContours(img_1, contours, -1, (0, 255, 0), 2)

    # display the output
    plt.imshow(img_1)
    break